package naga.x.util;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;

public class JSONArrayTypeHandler<E, L extends List<E>> extends BaseTypeHandler<L> {

	private Class<E> type;
	
	public JSONArrayTypeHandler(Class<E> type) {
		this.type = type;
	}
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, L parameter, JdbcType jdbcType) throws SQLException {
		ps.setString(i, JSON.toJSONString(parameter));
	}

	@Override
	public L getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public L getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public L getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}

	@SuppressWarnings("unchecked")
	private L parse(String text) throws SQLException {
		L list = null;
		if (StringUtils.isNotEmpty(text)) {
			list = (L) JSON.parseArray(text, type);
		}
		return list;
	}

}
